Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
Agregue una función al prototipo con acceso a "esto"

Por un lado, puedo asignar una nueva función a un objeto con Object.defineProperty(...) .

Luego traté de asignar una función directamente al prototipo NodeList. Pero de alguna manera no funciona correctamente. ¿Qué estoy haciendo mal?

 Object.defineProperty( NodeList.prototype, 'lastElement', { get: function() { return this[this.length - 1].textContent; } } ); NodeList.prototype.firstElement = () => { return this[0].textContent; } const h = document.querySelectorAll('span'); console.log('#last:', h.lastElement); console.log('#first:', h.firstElement);
 <div> <span>1</span> <span>2</span> </div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Las funciones de flecha () => {...} no son solo una sintaxis diferente que se comporta de la misma manera, en realidad manejan this palabra clave de manera diferente.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#arrow_functions_used_as_methods

Si cambia a usar la sintaxis de función tradicional, this comportará como espera.

Además, ha definido firstElement como una función regular, no como una función getter, por lo que deberá llamarlo así

 console.log('#first:', h.firstElement()); 

 Object.defineProperty( NodeList.prototype, 'lastElement', { get: function() { return this[this.length - 1].textContent; } } ); NodeList.prototype.firstElement = function() { return this[0].textContent; } const h = document.querySelectorAll('span'); console.log('#last:', h.lastElement); console.log('#first:', h.firstElement());
 <div> <span>1</span> <span>2</span> </div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!